<?php

namespace App\Jobs;

use App\Models\ScoreLogs;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class AddPkScore implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $roomId;

    public $userId;

    public $pkUserId;

    public $isWin;

    /**
     * @param  string $roomId
     * @param  int $userId
     * @param  int $pkUserId
     * @param  int $isWin
     * @return void
     */
    public function __construct($roomId, $userId, $pkUserId, $isWin)
    {
        $this->roomId = $roomId;
        $this->userId = $userId;
        $this->pkUserId = $pkUserId;
        $this->isWin = $isWin;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        ScoreLogs::$userId = $this->userId;

        // 今日已 PK 次数
        $pkCount = ScoreLogs::query()
            ->where('is_win', '<', 3)
            ->where('user_id', $this->userId)
            ->where('created_at', '>', Carbon::today())
            ->count();

        // 获得能量（每天前 10 次，获胜得 5 能量，失败得 1 能量）
        $score = 0;
        if ($pkCount < 10) {
            $score = $this->isWin == 1 ? 5 : 1;

            User::query()->where('id', $this->userId)->increment('score', $score);
        }

        // 能量值日志
        ScoreLogs::query()->insertOrIgnore([
            'room_id' => $this->roomId,
            'user_id' => $this->userId,
            'pk_user_id' => $this->pkUserId,
            'is_robot' => $this->pkUserId ? 0 : 1,
            'is_win' => $this->isWin, // 是否胜利 0 失败 1 胜利 2 平局 3 自测
            'score' => $score,
            'created_at' => now(),
        ]);
    }
}
